package com.aspire.boc.mms.wmf.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aspire.boc.mms.wmf.model.Ext4JsTreeNode;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * 资源树工具类
 * @author zhanghao
 *
 */
public class ResourceTreeUtil {

	/**
	 * 拼装资源树(json格式)
	 * @param allTreeNodeList
	 * @param rootResourceId
	 * @return
	 */
	public static JSONObject assembleExt4JsTree(List<Ext4JsTreeNode> allTreeNodeList, Integer rootResourceId) {

		Map<Integer, Ext4JsTreeNode> allTreeNodeMap = new HashMap<Integer, Ext4JsTreeNode>();
		
		if(rootResourceId == null)
			rootResourceId = 0;
		Ext4JsTreeNode rootTreeNode = new Ext4JsTreeNode();
		rootTreeNode.setResourceId(rootResourceId);
		allTreeNodeMap.put(rootResourceId, rootTreeNode);
		allTreeNodeList.add(rootTreeNode);
		
		for(Ext4JsTreeNode treeNode : allTreeNodeList) {
			Integer resourceId = treeNode.getResourceId();
			if(!allTreeNodeMap.containsKey(resourceId)) {
				allTreeNodeMap.put(resourceId, treeNode);
			}
		}
		
		for(Ext4JsTreeNode treeNode : allTreeNodeList) {
			Integer parentid = treeNode.getParentResourceId();
			if(parentid == null || !allTreeNodeMap.containsKey(parentid)) {
				continue;
			}
			Ext4JsTreeNode parentResource = allTreeNodeMap.get(parentid);
			List<Integer> children = parentResource.getChildrenIds();
			if(children == null) {
				children = new ArrayList<Integer>();
			}
			children.add(treeNode.getResourceId());
			parentResource.setChildrenIds(children);
		}
		
		JSONObject jsonTree = addChildren(rootTreeNode, allTreeNodeMap);
		return jsonTree;
	}
	
	private static JSONObject addChildren(Ext4JsTreeNode rootTreeNode, Map<Integer, Ext4JsTreeNode> allTreeNodeMap) {
		
		JSONObject jsonObject = JSONObject.fromObject(rootTreeNode);
		if(rootTreeNode.getChildrenIds() != null) {
			for(Integer childId : rootTreeNode.getChildrenIds()) {
				Ext4JsTreeNode treeNode = allTreeNodeMap.get(childId);
				JSONArray tmpJsonArray = null;
				try {
				  tmpJsonArray = jsonObject.getJSONArray("children");
				} catch(JSONException e) {
				}
				if(tmpJsonArray == null) 
					tmpJsonArray = new JSONArray();
				tmpJsonArray.add(addChildren(treeNode, allTreeNodeMap));
				jsonObject.put("children", tmpJsonArray);
			}
		}
		return jsonObject;
	}
}
